package com.qf.intercepter;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.BaseResp;
import com.qf.utils.JwtUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class MyIntercpter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();

        if(cookies!=null&&cookies.length>0) {
            String token = null;
            for (Cookie cook : cookies
            ) {
                if (cook.getName().equals("token")) {
                    token = cook.getValue();
                }
            }
            System.out.println(token);
            if (token!=null){
                JwtUtils jwtUtils = new JwtUtils();
                String name=null;
                try {
                    name  = jwtUtils.verfiyToken(token);
                    System.out.println(name);
                }catch (Exception e){

                }
                if (!StringUtils.isEmpty(name)){
                    return true;
                }

            }

        }
        BaseResp baseresp = new BaseResp();
        baseresp.setMgs("用户未登录");
        baseresp.setCode(205);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(baseresp));
        return false;
    }
}
